import { ROUTE_PATHS } from "./routes";
import store from "@/store";

/**
 * 角色配置
 */
export const ROLES = {
  USER: "user",
  PROFESSOR: "professor",
  // ROLES.GUEST 表示所有人都可以访问的路由
  GUEST: "guest",
};

/**
 * 路由权限配置
 */
export const ROUTE_PERMISSION = {
  [ROUTE_PATHS.INDEX]: {
    roles: [ROLES.GUEST],
  },
  [ROUTE_PATHS.LOGIN]: {
    roles: [ROLES.GUEST],
  },
  [ROUTE_PATHS.HOME]: {
    roles: [ROLES.GUEST],
  },
  [ROUTE_PATHS.SEARCH]: {
    roles: [ROLES.GUEST],
  },
  [ROUTE_PATHS.APPOINTMENT]: {
    roles: [ROLES.USER],
    redirect: ROUTE_PATHS.LOGIN,
  },
  [ROUTE_PATHS.APPOINTMENT_DETAIL]: {
    roles: [ROLES.USER],
    redirect: ROUTE_PATHS.LOGIN,
  },
  [ROUTE_PATHS.APPOINTMENT_LIST]: {
    roles: [ROLES.USER],
    redirect: ROUTE_PATHS.LOGIN,
  },
  [ROUTE_PATHS.USER_CENTER]: {
    roles: [ROLES.USER],
    redirect: ROUTE_PATHS.LOGIN,
  },
  [ROUTE_PATHS.CONFIRM]: {
    roles: [ROLES.GUEST],
  },
  [ROUTE_PATHS.AUDIT]: {
    roles: [ROLES.PROFESSOR],
    redirect: ROUTE_PATHS.CONFIRM,
  },
};

/**
 * 获取当前角色
 * @returns {string} 当前角色
 */
export function getCurrentRole() {
  const userToken = store.state.user.token;
  const professorToken = store.state.professor.token;
  if (userToken) {
    return ROLES.USER;
  } else if (professorToken) {
    return ROLES.PROFESSOR;
  } else {
    return ROLES.GUEST;
  }
}

/**
 * 获取路由权限配置
 * @param {string} routePath 路由路径
 * @returns {Object} 路由权限配置
 */
function getPermissionConfig(routePath) {
  const routeConfig = ROUTE_PERMISSION[routePath];
  if (!routeConfig) {
    throw new Error(`路由配置不存在: ${routePath}`);
  }
  return routeConfig;
}

/**
 * 检查路由权限
 * @param {string} routePath 路由路径
 * @returns {boolean} 是否具有权限
 */
export function checkPermission(routePath) {
  const permissionConfig = getPermissionConfig(routePath);
  const role = getCurrentRole();
  return (
    permissionConfig.roles.includes(ROLES.GUEST) ||
    permissionConfig.roles.includes(role)
  );
}

/**
 * 获取路由重定向路径
 * @param {string} routePath 路由路径
 * @returns {string} 重定向路径
 */
export function getRedirectPath(routePath) {
  const permissionConfig = getPermissionConfig(routePath);
  if (permissionConfig.redirect) {
    return permissionConfig.redirect;
  } else {
    return ROUTE_PATHS.HOME;
  }
}